package
{
	import flash.display.MovieClip;

	public class csSound
	{
		private var _mc:MovieClip;
		private var _attachedTracks:Array = new Array();
		private var _attachingSoundId:String;
		
		public function csSound(mc:MovieClip)
		{
			if(mc == null)
			{
				trace("not support global csSound");
			}

			_mc = mc;
		}
		
		private function collectMcInTree(mc:MovieClip, mcs:Array):void
		{
			if(mc != null)
			{
				mcs.push(mc);
				
				var n:int = mc.numChildren;
				for(var i:int = 0; i < n; ++i)
				{
					collectMcInTree(mc.getChildAt(i) as MovieClip, mcs);
				}
			}
		}

		public function setVolume(v:Number):void
		{
			var track:csSoundTrack;
			
			var mcs:Array = new Array();
			collectMcInTree(_mc, mcs);
			
			for each(var mc:MovieClip in mcs)
			{
				if(mc != null)
				{
					var tracks:Array = mc[_attribute.ATTR_SOUND_TRACKS];
					for each(track in tracks)
					{
						track.setVolume(v);
					}
				}
				
			}
			
			for each(track in _attachedTracks)
			{
				track.setVolume(v);
			}
			
			_mc[_attribute.ATTR_SOUND_VOLUME] = v;
		}
		
		public function setPan(v:Number):void
		{
			var track:csSoundTrack;
			
			var mcs:Array = new Array();
			collectMcInTree(_mc, mcs);
			
			for each(var mc:MovieClip in mcs)
			{
				if(mc != null)
				{
					var tracks:Array = mc[_attribute.ATTR_SOUND_TRACKS];
					for each(track in tracks)
					{
						track.setPan(v);
					}
				}
				
			}
			
			for each(track in _attachedTracks)
			{
				track.setPan(v);
			}
			
			_mc[_attribute.ATTR_SOUND_PAN] = v;
		}
		
		public function start(loops:int):void
		{
			var track:csSoundTrack;
			
			var mcs:Array = new Array();
			collectMcInTree(_mc, mcs);
			
			for each(var mc:MovieClip in mcs)
			{
				if(mc != null)
				{
					var tracks:Array = mc[_attribute.ATTR_SOUND_TRACKS];
					for each(track in tracks)
					{
						track.start(loops);
					}
				}
				
			}
			
			for each(track in _attachedTracks)
			{
				track.start(loops);
			}
			
			if(_attachingSoundId != null)
			{
				var attachingTrack:csSoundTrack = new csSoundTrack(null, _attachingSoundId, -1);
				attachingTrack.start(loops);

				_attachedTracks.push(attachingTrack);
				attachingTrack = null;
			}
			
		}
		
		public function stop():void
		{
			var track:csSoundTrack;
			
			var mcs:Array = new Array();
			collectMcInTree(_mc, mcs);
			
			for each(var mc:MovieClip in mcs)
			{
				if(mc != null)
				{
					var tracks:Array = mc[_attribute.ATTR_SOUND_TRACKS];
					for each(track in tracks)
					{
						track.stop();
					}
				}
				
			}
			
			for each(track in _attachedTracks)
			{
				track.stop();
			}
		}
		
		public function attachSound(id:String):void
		{
			_attachingSoundId = id;
		}
		
	}
}